package com.colbby.datahouse.message.handler;

import java.util.List;

import org.jinghouyu.json.core.JsonObject;

import com.colbby.datahouse.database.ObjectInserter;
import com.colbby.datahouse.shop.TopUtils;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.response.TradeFullinfoGetResponse;

public class TradeHandler implements ContentHandler {

	@Override
	public boolean check(JsonObject json) {
		return true;
	}
	
	@Override
	public void handle(JsonObject json) {
		String fields = "tid,created,modified,seller_nick,status,type,price,total_fee,payment,post_fee,real_point_fee,commission_fee,code_fee,adjust_fee,pay_time,end_time,consign_time,alipay_no,buyer_nick,shipping_type," +
				"received_payment,receiver_city,receiver_district,receiver_name,receiver_state,receiver_address,receiver_zip,receiver_mobile,receiver_phone";
		String shopNick = json.getString("seller_nick");
		Long tid = json.getLong("tid");
		String sessionKey = TopUtils.getSessionKey(shopNick);
		TaobaoClient client = TopUtils.getTaobaoClient();
		TradeFullinfoGetRequest request = new TradeFullinfoGetRequest();
		request.setTid(tid);
		request.setFields(fields);
		try {
			TradeFullinfoGetResponse response = client.execute(request, sessionKey);
			if(!response.isSuccess()) {
				throw new RuntimeException(response.getBody());
			}
			Trade trade = response.getTrade();
			if(trade == null) return;
			com.colbby.datahouse.entity.Trade _trade = com.colbby.datahouse.entity.Trade.fromTaobao(trade);
			List<Object> entities = _trade.seperate();
			for(Object entity : entities) {
				ObjectInserter.instance().insert(entity);
			}
		} catch (ApiException e) {
			throw new RuntimeException(e);
		}
	}
}
